﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Practices.Unity;
using WebShop.Contracts;
using WebShop.DAL.Interfaces;
using Webdiyer.WebControls.Mvc;

namespace WebShop.DAL.Repositories
{
    public class CategoryReository : ICategoryRepository
    {
        [Dependency]
        public NWData DbContext { get; set; }

        public void Create(Category objectToCreate)
        {
            DbContext.DataContext.Categories.Add(objectToCreate);
        }

        public void Delete(int id)
        {
            DbContext.DataContext.Entry(Get(id)).State = EntityState.Deleted;
        }

        public void Edit(Category objectToUpdate)
        {
            DbContext.DataContext.Entry(objectToUpdate).State = EntityState.Modified;
        }

        public Category Get(int id)
        {
            return DbContext.DataContext.Categories.Find(id);
        }

        public Category Find(System.Linq.Expressions.Expression<Func<Category, bool>> predicate)
        {
            return DbContext.DataContext.Categories.SingleOrDefault(predicate);
        }

        public IEnumerable<Category> List()
        {
            return DbContext.DataContext.Categories.ToList();
        }

        public PagedList<Category> List(int? page, int pageSize)
        {
            return DbContext.DataContext.Categories.ToPagedList(page.GetValueOrDefault(1), pageSize);
        }

        public PagedList<Category> FindList(int? page, int pageSize, System.Linq.Expressions.Expression<Func<Category, bool>> predicate, System.Linq.Expressions.Expression<Func<Category, string>> orderBy, bool ascending)
        {
            var query = DbContext.DataContext.Categories.AsQueryable();


            if (predicate != null)
            {
                query = query.Where(predicate);
            }

            if (orderBy != null)
            {
                if (ascending)
                {
                    query = query.OrderBy(orderBy);
                }
                else
                {
                    query = query.OrderByDescending(orderBy);
                }
            }
            else
            {
                query = query.OrderBy(c => c.CategoryName);
            }

            return query.ToPagedList(page.GetValueOrDefault(1), pageSize);
        }

        public void SaveChanges()
        {
            DbContext.DataContext.SaveChanges();
        }


        public void Detach(Category objectToDetach)
        {
            DbContext.DataContext.Entry(objectToDetach).State = EntityState.Detached;
        }
    }
}